using Microsoft.AspNetCore.Mvc;
using mvc.Models;
using System;
using Microsoft.EntityFrameworkCore;
using mvc.Db;
using System.Linq;
using mvc.IR;
using System.Collections.Generic;
namespace mvc.Controllers
{
    public class BookController:Controller
    {
        public ERe<Book> _Rbook = new ERe<Book>();
        public ERe<Library> _Rlibrary = new ERe<Library>();
        public IList<Book> book;
        public IActionResult Index()
        {
            if(_Rlibrary.table.FirstOrDefault()==null){
                _Rlibrary.Insert(new Library
                {
                    BookName="哈哈哈"
                });
            }

            book = _Rbook.table.Where(x=>x.IsDelete==false).ToList();

            return View(book);
        }

        public IActionResult AddorEndit(int id){
            ViewBag.l = _Rlibrary.table;
            if(id==0){
                return View();
            }
            var book = _Rbook.table.Where(x=>x.Id==id).FirstOrDefault();
            return View(book);
        }
        public IActionResult Save(BookObj obj){

            if(obj.Id==0){
                _Rbook.Insert(new Book{
                    BookName = obj.BookName,
                    LibraryId=obj.LibraryId
                });
            
            }
            else{
                var book = _Rbook.table.Where(x=>x.Id==obj.Id).FirstOrDefault();
                book.BookName=obj.BookName;
                book.LibraryId=obj.LibraryId;
                _Rbook.Update(book);
            }

            return Ok();
        }

        public IActionResult Delete(int id){
            if(_Rbook.table.Where(x=>x.Id==id).FirstOrDefault()!=null){
                _Rbook.Delete(id); 
            }
            return RedirectToAction("Index");
        }

        public IActionResult Select(SelectObj obj){
            if(obj.Select=="1"){
                book = _Rbook.table.Where(x=>x.IsDelete==false&&x.BookName.Contains(obj.Str)).ToList();
            }else if(obj.Select=="2"){
                book = _Rbook.table.Where(x=>x.IsDelete==false&& x.Id==int.Parse(obj.Str)).ToList();
            }else{
                book = _Rbook.table.Where(x=>x.IsDelete==false&& x.LibraryId==int.Parse(obj.Str)).ToList();
            }
            return Json(book);
        }

    }
}